/*
 * @Author: yt 2399493770@qq.com
 * @Date: 2024-04-25 22:47:32
 * @LastEditors: yt 2399493770@qq.com
 * @LastEditTime: 2024-04-26 00:44:02
 * @Description:
 */
import { Request, Response } from "express";
import { verify } from "jsonwebtoken";

const { NEXT_PUBLIC_ACCESS_TOKEN_SECRET } = process.env;
/**
 * 校验token是否过期或存在
 * @param req
 * @param isJwt 是否需要校验token
 * @returns
 */
export function jwtMiddleware(req: Request, isJwt: boolean) {
  const tokens = req.headers.tokens as string;

  return new Promise((resolve, reject) => {
    try {
      // 跳过校验
      if (!isJwt) resolve(null);
      const decoded = verify(tokens, NEXT_PUBLIC_ACCESS_TOKEN_SECRET ?? "");
      resolve(decoded);
    } catch (error) {
      reject(error);
    }
  });
}